//
//  UpdateViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/7/25.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "UpdateViewController.h"
#import <AFNetworking.h>

@interface UpdateViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    UIButton *imageBtn;
}

@property (nonatomic, strong) UILabel *noteLabel1;
@property (nonatomic, strong) UILabel *noteLabel2;
@property (nonatomic, strong) UILabel *noteLabel3;
@property (nonatomic, strong) UILabel *noteLabel4;

@property (nonatomic, strong) NSArray *noteLabelArr;
@property (nonatomic, strong) NSMutableArray *selectChannel;
@property (nonatomic, strong) UIImage *selectImage;

@property (nonatomic, strong) UIView *secondView;
@property (nonatomic, copy)   NSString *secondStr;

@property (nonatomic, strong) UIImagePickerController *pickerController;

@end

@implementation UpdateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"上传海报";
    _selectChannel = [NSMutableArray array];
    _secondStr = @"";
    
    [self setUI];
    
    self.pickerController = [[UIImagePickerController alloc] init];
    self.pickerController.delegate = self;
}

- (void)setUI {
    imageBtn = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(337)) / 2, ScreenX375(10), ScreenX375(337), ScreenX375(337))];
    imageBtn.layer.cornerRadius = ScreenX375(8);
    imageBtn.clipsToBounds = YES;
    [imageBtn setImage:ImageWithName(@"添加") forState:UIControlStateNormal];
    imageBtn.backgroundColor = REXADECIMALCOLOR(@"#f2f2f2");
    [imageBtn addTarget:self action:@selector(selectBgImage) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:imageBtn];
    
    self.noteLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(16), ScreenX375(92), ScreenX375(36))];
    self.noteLabel1.backgroundColor = RGB_COLOR(255, 208, 0);
    self.noteLabel1.layer.cornerRadius = ScreenX375(4);
    self.noteLabel1.alpha = 0.8;
    self.noteLabel1.textAlignment = NSTextAlignmentCenter;
    self.noteLabel1.textColor = [UIColor whiteColor];
    self.noteLabel1.font = KBlodfont(16);
    self.noteLabel1.clipsToBounds = YES;
    self.noteLabel1.hidden = YES;
    [imageBtn addSubview:self.noteLabel1];
    
    self.noteLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(62), ScreenX375(70), ScreenX375(24))];
    self.noteLabel2.backgroundColor = RGBACOLOR(0, 0, 0, 0.5);
    self.noteLabel2.layer.cornerRadius = ScreenX375(4);
    self.noteLabel2.textAlignment = NSTextAlignmentCenter;
    self.noteLabel2.textColor = [UIColor whiteColor];
    self.noteLabel2.font = KBlodfont(11);
    self.noteLabel2.clipsToBounds = YES;
    self.noteLabel2.hidden = YES;
    [imageBtn addSubview:self.noteLabel2];
    
    self.noteLabel3 = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(96), ScreenX375(70), ScreenX375(24))];
    self.noteLabel3.backgroundColor = RGBACOLOR(0, 0, 0, 0.5);
    self.noteLabel3.layer.cornerRadius = ScreenX375(4);
    self.noteLabel3.textAlignment = NSTextAlignmentCenter;
    self.noteLabel3.textColor = [UIColor whiteColor];
    self.noteLabel3.font = KBlodfont(11);
    self.noteLabel3.clipsToBounds = YES;
    self.noteLabel3.hidden = YES;
    [imageBtn addSubview:self.noteLabel3];
    
    self.noteLabel4 = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(130), ScreenX375(70), ScreenX375(24))];
    self.noteLabel4.backgroundColor = RGBACOLOR(0, 0, 0, 0.5);
    self.noteLabel4.layer.cornerRadius = ScreenX375(4);
    self.noteLabel4.textAlignment = NSTextAlignmentCenter;
    self.noteLabel4.textColor = [UIColor whiteColor];
    self.noteLabel4.font = KBlodfont(11);
    self.noteLabel4.clipsToBounds = YES;
    self.noteLabel4.hidden = YES;
    [imageBtn addSubview:self.noteLabel4];
    
    self.noteLabelArr = @[self.noteLabel2,self.noteLabel3,self.noteLabel4];
    
    UILabel *firstLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(19), ScreenX375(368), ScreenX375(90), ScreenX375(18))];
    firstLabel.text = @"一级标题";
    firstLabel.textColor = FONTCOLOR_BLACK;
    firstLabel.font = KBlodfont(16);
    [self.view addSubview:firstLabel];
    
    UILabel *firstNoteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(88), ScreenX375(370), ScreenX375(90), ScreenX375(16))];
    firstNoteLabel.text = @"只能填写1个";
    firstNoteLabel.textColor = REXADECIMALCOLOR(@"#f21934");
    firstNoteLabel.font = Kfont(12);
    [self.view addSubview:firstNoteLabel];
    
    UIButton *firstBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(397), ScreenX375(120), ScreenX375(32))];
    firstBtn.titleLabel.font = Kfont(16);
    [firstBtn setTitleColor:FONTCOLOR_BLACK forState:UIControlStateNormal];
    firstBtn.layer.cornerRadius = ScreenX375(16);
    firstBtn.layer.borderColor = REXADECIMALCOLOR(@"#eaeaea").CGColor;
    firstBtn.layer.borderWidth = 1;
    [firstBtn addTarget:self action:@selector(selectFirstTitle:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:firstBtn];
    
    UILabel *secondLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(19), ScreenX375(448), ScreenX375(90), ScreenX375(18))];
    secondLabel.text = @"二级标题";
    secondLabel.textColor = FONTCOLOR_BLACK;
    secondLabel.font = KBlodfont(16);
    [self.view addSubview:secondLabel];
    
    UILabel *secondNoteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(88), ScreenX375(450), ScreenX375(90), ScreenX375(16))];
    secondNoteLabel.text = @"最多填写3个";
    secondNoteLabel.textColor = REXADECIMALCOLOR(@"#f21934");
    secondNoteLabel.font = Kfont(12);
    [self.view addSubview:secondNoteLabel];
    
    self.secondView = [[UIView alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(473), SCREEN_WIDTH, ScreenX375(35))];
    [self.view addSubview:self.secondView];
    
    [self setSecondView];
    
    UIButton *sureBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - ScreenX375(44) - NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, ScreenX375(44))];
    [sureBtn setTitle:@"提交" forState:UIControlStateNormal];
    sureBtn.titleLabel.font = Kfont(16);
    [sureBtn setTitleColor:REXADECIMALCOLOR(@"#ffffff") forState:UIControlStateNormal];
    [sureBtn setBackgroundImage:ImageWithName(@"按钮背景") forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(sure) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureBtn];
}

- (void)setSecondView {
    for (UIView *subView in self.secondView.subviews) {
        [subView removeFromSuperview];
    }
    for (int j = 0; j < 3; j++) {
        UILabel *noteLabel = self.noteLabelArr[j];
        if (j < _selectChannel.count) {
            noteLabel.text = _selectChannel[j];
            CGFloat width = kGetStringWidth(noteLabel.text, CGSizeMake(ScreenX375(200), ScreenX375(24)), KBlodfont(11));
            noteLabel.frame = CGRectMake(ScreenX375(16), noteLabel.frame.origin.y, width + ScreenX375(28), ScreenX375(24));
            noteLabel.hidden = NO;
        }else {
            noteLabel.text = @"";
            noteLabel.hidden = YES;
        }
    }
    for (int i = 0; i < _selectChannel.count + 1; i++) {
        UIButton *secondBtn = [[UIButton alloc] initWithFrame:CGRectMake(i * ScreenX375(120), ScreenX375(3), ScreenX375(106), ScreenX375(32))];
        secondBtn.titleLabel.font = Kfont(16);
        [secondBtn setTitleColor:FONTCOLOR_BLACK forState:UIControlStateNormal];
        secondBtn.layer.cornerRadius = ScreenX375(16);
        secondBtn.layer.borderColor = REXADECIMALCOLOR(@"#eaeaea").CGColor;
        secondBtn.layer.borderWidth = 1;
        [secondBtn addTarget:self action:@selector(selectSecondTitle:) forControlEvents:UIControlEventTouchUpInside];
        [self.secondView addSubview:secondBtn];
        
        if (i < _selectChannel.count) {
            [secondBtn setTitle:_selectChannel[i] forState:UIControlStateNormal];
            
            UIButton *deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(92) + i * ScreenX375(120), 0, ScreenX375(15), ScreenX375(15))];
            [deleteBtn setImage:ImageWithName(@"删除标签") forState:UIControlStateNormal];
            deleteBtn.tag = 500 + i;
            [deleteBtn addTarget:self action:@selector(deleteSecond:) forControlEvents:UIControlEventTouchUpInside];
            [self.secondView addSubview:deleteBtn];
        }else {
            [secondBtn setImage:ImageWithName(@"添加2") forState:UIControlStateNormal];
        }
    }
}

- (void)sure {
    if (!_selectImage) {
        [HttpManager showNoteMsg:@"请选择海报图片"];
        return;
    }
    if (self.noteLabel1.text.length == 0) {
        [HttpManager showNoteMsg:@"请填写一级标题"];
        return;
    }
    if (_selectChannel.count <2) {
        [HttpManager showNoteMsg:@"请至少填写两个二级标题"];
        return;
    }
    NSMutableArray *dataArr = [NSMutableArray arrayWithObject:_selectImage];
    [HttpManager uploadImageArr:dataArr success:^(id successResponse) {
        NSString *imageStr = successResponse[0];
        NSDictionary *parameter = @{@"pic":imageStr,@"userId":kNSUDefaultReadKey(@"userId"),@"title":self.noteLabel1.text,@"titleOne":self.noteLabel2.text,@"titleTwo":self.noteLabel3.text,@"titleThree":self.noteLabel4.text};
        [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@api/uploadPoster",REQUESTHEADER] andParameter:parameter success:^(id successResponse) {
            if ([successResponse[@"code"] integerValue] == 200) {
                [HttpManager hideWait];
                [HttpManager showNoteMsg:@"发布成功"];
                [self.navigationController popToRootViewControllerAnimated:YES];
                [kNotificationCenter postNotificationName:@"ReloadFoundList" object:self userInfo:nil];
            }else{
                [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"message"]]];
            }
        } andFailure:^(id failureResponse) {
            [HttpManager showNoteMsg:@"上传失败"];
        }];
    }];
}

- (void)selectFirstTitle:(UIButton *)button {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请输入一级标题" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        [textField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (self.noteLabel1.text.length == 0) {
            [HttpManager showNoteMsg:@"请输入一级标题"];
            return ;
        }
        [button setTitle:self.noteLabel1.text forState:UIControlStateNormal];
        CGFloat width = kGetStringWidth(self.noteLabel1.text, CGSizeMake(ScreenX375(200), ScreenX375(36)), KBlodfont(16));
        self.noteLabel1.frame = CGRectMake(ScreenX375(16), ScreenX375(16), width + ScreenX375(28), ScreenX375(36));
        self.noteLabel1.hidden = NO;
    }];
    
    [alertController addAction:cancel];
    [alertController addAction:sure];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)textFieldChange:(UITextField *)textField {
    _noteLabel1.text = textField.text;
}

- (void)textFieldChange2:(UITextField *)textField {
    self.secondStr = textField.text;
}

- (void)deleteSecond:(UIButton *)button {
    [self.selectChannel removeObjectAtIndex:button.tag - 500];
    [self setSecondView];
}

- (void)selectSecondTitle:(UIButton *)button {
    if (button.titleLabel.text.length == 0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请输入二级标题" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            [textField addTarget:self action:@selector(textFieldChange2:) forControlEvents:UIControlEventEditingChanged];
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (self.secondStr.length == 0) {
                [HttpManager showNoteMsg:@"请输入二级标题"];
                return ;
            }
            [self.selectChannel addObject:self.secondStr];
            self.secondStr = @"";
            [self setSecondView];
        }];
        
        [alertController addAction:cancel];
        [alertController addAction:sure];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

- (void)selectBgImage {
    [self.view endEditing:YES];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *send = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.pickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        self.pickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        [self presentViewController:self.pickerController animated:YES completion:nil];
    }];
    UIAlertAction *get = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        self.pickerController.allowsEditing = YES;
        [self presentViewController:self.pickerController animated:YES completion:nil];
    }];
    
    [alert addAction:cancel];
    [alert addAction:send];
    [alert addAction:get];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [imageBtn setImage:image forState:UIControlStateNormal];
    _selectImage = image;
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self.pickerController dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
